<?php
// $Id$

/**
 * Controller_Admin_Projects controller
 */
class Controller_Admin_Projects extends Controller_Abstract
{
	function actionIndex()
    {
        $this->_view['form'] = Form_Admin_Project::createSearchForm(url('projects/search'));
    }

    function actionSearch()
    {
        $name = $this->_context->name;
        $select = Project::find();
        if (empty($name))
        {
            $title = $this->_context->title;
            if ($title)
            {
                $select->where('title LIKE ?', "%{$title}%");
            }
        }
        else
        {
            $select->where('name LIKE ?', "%{$name}%");
        }

        $this->_view['projects'] = $select->getAll();
    }

    function actionEdit()
    {
        $id = $this->_context->id;
        $project = Project::find('id = ?', $id)->query();
        if (!$project->id())
        {
            return $this->_redirect(url('projects/index'));
        }
        $form = Form_Admin_Project::createForm(url('projects/edit'));

        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            try
            {
                $project->is_picked        = $form['is_picked']->value;
                $project->is_homepage      = $form['is_homepage']->value;
                $project->is_homepage_hot  = $form['is_homepage_hot']->value;
                $project->is_approbated    = $form['is_approbated']->value;
                $project->homepage_title   = $form['homepage_title']->value;
                $project->homepage_excerpt = $form['homepage_excerpt']->value;
                $project->save();

                return $this->_redirect(url('projects/edit', array('id' => $project->id())));
            }
            catch (QValidator_ValidateFailedException $ex)
            {
                $form->invalidate($ex);
            }
        }
        elseif (!$this->_context->isPOST())
        {
            $form->import($project);
            $form['is_picked']->checked       = $project->is_picked;
            $form['is_homepage']->checked     = $project->is_homepage;
            $form['is_homepage_hot']->checked = $project->is_homepage_hot;
            $form['is_approbated']->checked   = $project->is_approbated;
        }

        $this->_view['form'] = $form;
    }

    function actionClean()
    {
        $this->_view['projects'] = Project::find('is_pending_delete = ?', true)->getAll();
        $this->_viewname = 'search';
    }

    function actionUpdate()
    {
        $delete = (array)$this->_context->delete;
        if (!empty($delete))
        {
            Project::meta()->destroyWhere('id IN (?)', $delete);
        }
        return $this->_redirect(url('projects/index'));
    }

}


